package sws;

/**
 * Ping tactic for sensor availability
 */
public class Ping extends Thread implements ISensor {
	private EmuSensor es;
	private String[] data;

	@Override
	public void connect() {
		es = null;
		es = new EmuSensor(new String[1]);
		es.start();
	}

	@Override
	public void run() {
		double s = System.currentTimeMillis();

		for(int i = 0; i < 50; i++) {
			if(failureDetection())
				System.out.println("Timestep " + i + ": " + data[0]);
			else
				break;

			try {
				// Intervals of measurements
				Thread.sleep(250);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		es.kill();
		System.out.println("50 measurements with 2 sensor kills: "+ ((System.currentTimeMillis() - s)/1000) + " sec.");
	}

	/**
	 * Ensuring that there is a connection to the sensor. If the sensor is down a new
	 * connection is made.
	 * 
	 * In this implementation a defect sensor might cause an infinite loop.
	 * 
	 * @return true
	 */
	private boolean failureDetection() {
		if(es == null || !es.isAlive())
			connect();
		
		data = es.getData().clone();

		while(data == null) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		return true;
	}

	@Override
	public void killSensor() {
		es.kill();
		es = null;
	}
}
